// search.js

Page({
  data: {
    result: {
      name: "",
      type: 0,
      aipre: 0,
      explain: "",
      contain: "",
      tip: ""
    }
  },
  onLoad() {
    this.setData({
      search: this.search.bind(this)
    })
  },
  search: function (value) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://api.tianapi.com/txapi/lajifenlei/index?key=' + APIKEY + '&word=' + value,
        success: function (res) {
          if (res.data.code == 200) {
            results = res.data.newslist
            resolve(parseRes(results))
          } else {
            console.log(res.data.msg)
          }
        },
        fail: function (err) {
          console.log(err)
        }
      })
    })
  },
  selectResult: function (e) {
    this.selectComponent('#searchBar').hideInput()
    this.setData({
      result: results[e.detail.index]
    })
  },
});

var APIKEY = "1d574ffc1e47fa65274294e074b361f1";
var results = []

function parseRes(results) {
  var nameList = []
  var value = 1
  results.forEach(element => {
    nameList.push({
      text: element.name,
      value: value++
    })
  });
  return nameList
}
